package com.baizhi.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 这是MyBats的配置类
 */
public class MyBatisConfig {



    //创建SQLSessionFactoryBean对象
    @Bean
    public SqlSessionFactoryBean createSqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //设置数据源
        factoryBean.setDataSource(dataSource);
        //起别名
        factoryBean.setTypeAliasesPackage("com.baizhi.pojo");

        //设置条件
        Configuration configuration = new Configuration();
        //配置驼峰命名规则
        configuration.setMapUnderscoreToCamelCase(true);
        //开启MyBatis自动映射
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);

        //把条件添加到factoryBean中
        factoryBean.setConfiguration(configuration);

        //添加分页插件
        PageInterceptor pageInterceptor = new PageInterceptor();
        /*
            <!-- 表示使用mysql的分页方法 -->
          <property name="helperDialect" value="mysql" />
          <!-- 表示当页码长度为0 的时候,就不进行分页查询 -->
          <property name="pageSizeZero" value="true"/>
         */
        Properties properties = new Properties();
        properties.setProperty("helperDialect","MySQL");
        properties.setProperty("pageSizeZero","true");
        pageInterceptor.setProperties(properties);

        factoryBean.setPlugins(pageInterceptor);
        return factoryBean;
    }


    //创建Mapper接口扫描器对象
    @Bean
    public  MapperScannerConfigurer createMapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //设置接口的位置
        mapperScannerConfigurer.setBasePackage("com.baizhi.mapper");
        return mapperScannerConfigurer;
    }


    //创建事务管理器对象
    @Bean
    public TransactionManager createTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;

    }
}
